<template>
  <a-card class="glass-container" :bordered="false" body-style="height:100%;">
    <div class="login-form-wrapper">
      <div class="login-form-title">{{ $t('login.form.title') }}</div>

      <a-form
        ref="loginForm"
        :model="userInfo"
        class="login-form"
        layout="vertical"
        @submit="handleSubmit"
        size="large"
      >
        <a-form-item
          field="username"
          :rules="[
            { required: true, message: $t('login.form.userName.errMsg') },
          ]"
          :validate-trigger="['change', 'blur']"
          hide-label
        >
          <a-input v-model="userInfo.username" :placeholder="`请输入用户名`">
            <template #prefix>
              <icon-user />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item
          field="password"
          :rules="[
            { required: true, message: $t('login.form.password.errMsg') },
          ]"
          :validate-trigger="['change', 'blur']"
          hide-label
        >
          <a-input-password
            v-model="userInfo.password"
            :placeholder="`请输入密码`"
            allow-clear
          >
            <template #prefix>
              <icon-lock />
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item
          field="verifycode"
          :rules="[
            {
              required: true,
              message: '请输入验证码',
              validator: validateVerifycode,
            },
          ]"
          hide-label
        >
          <a-input
            v-model="userInfo.verifycode"
            ref="verifycode"
            placeholder="验证码"
            class="identifyinput"
            style="width: 230px"
          ></a-input>
          <div
            class="identifybox"
            @click="job.refreshCode"
            style="height: 100%"
          >
            <sidentify :identifyCode="job.identifyCode"></sidentify>
          </div>
        </a-form-item>
        <a-space :size="16" direction="vertical">
          <div class="login-form-password-actions">
            <a-checkbox
              checked="rememberPassword"
              :model-value="loginConfig.rememberPassword"
              @change="setRememberPassword as any"
            >
              {{ $t('login.form.rememberPassword') }}
            </a-checkbox>
          </div>
          <a-button type="primary" html-type="submit" long :loading="loading">
            {{ $t('login.form.login') }}
          </a-button>
        </a-space>
      </a-form>
    </div>
  </a-card>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useI18n } from 'vue-i18n';
  import { useStorage } from '@vueuse/core';
  import { useUserStore, useAppStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import type { LoginData } from '@/api/user';
  import Sidentify from './sidentify.vue';
  const router = useRouter();
  const { t } = useI18n();
  const errorMessage = ref('');
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();
  const appStore = useAppStore();
  // 验证码自定义验证规则
  const validateVerifycode = (value, callback) => {
    if (value === '') {
      callback(new Error('请输入验证码'));
    } else if (value !== job.identifyCode) {
      console.log('验证码:', value);
      callback(new Error('验证码不正确!'));
      job.refreshCode(); //初始化验证码
    } else {
      callback();
    }
  };

  const job = reactive({
    verifycode: ``,
    identifyCodes: '1234567890',
    identifyCode: ``,
    //验证码----start
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    refreshCode() {
      job.identifyCode = '';
      job.makeCode(job.identifyCodes, 4);
      userInfo.verifycode = '';
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        job.identifyCode +=
          job.identifyCodes[job.randomNum(0, job.identifyCodes.length)];
      }
      // console.log("job.identifyCode:", job.identifyCode);
    },
    //验证码----end
  });
  onMounted(() => {
    job.refreshCode(); //初始化验证码
  });
  const loginConfig = useStorage('login-config', {
    rememberPassword: true,
    username: '', // 演示默认值
    password: '', // demo default value
  });
  const userInfo = reactive({
    // username: loginConfig.value.username,
    // password: loginConfig.value.password,
    username: '',
    password: '',
    verifycode: ``,
  });

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) return;
    if (!errors) {
      setLoading(true);
      try {
        console.log(userInfo);

        await userStore.login(userInfo, (info) => {
          appStore.serverMenu = info.menu;
          console.log('174:userStore.login——callback(params:info)', info);
        });
        console.log('!!!=>>>', appStore.serverMenu);
        const { redirect, ...othersQuery } = router.currentRoute.value.query;
        const isChild = appStore.serverMenu[0].children?.length;
        const path_ = isChild
          ? `${appStore.serverMenu[0].path}/${appStore.serverMenu[0].children[0].path}`
          : appStore.serverMenu[0].path;
        console.log(path_);
        const name_ = isChild
          ? appStore.serverMenu[0].children[0].name
          : appStore.serverMenu[0].name;
        const title_ = isChild
          ? appStore.serverMenu[0].children[0].meta?.locale
          : appStore.serverMenu[0].meta?.locale;
        console.log(path_);
        userStore.detault_path = path_;
        userStore.detault_name = name_;
        router.push(path_);
        // router.push({
        //   name: (redirect as string) || appStore.serverMenu[0].name,
        //   query: {
        //     ...othersQuery,
        //   },
        // });
        Message.success(t('login.form.login.success'));
        const { rememberPassword } = loginConfig.value;
        const { username, password } = values;
        // 实际生产环境需要进行加密存储。
        // The actual production environment requires encrypted storage.
        loginConfig.value.username = rememberPassword ? username : '';
        loginConfig.value.password = rememberPassword ? password : '';
      } catch (err) {
        errorMessage.value = (err as Error).message;
      } finally {
        setLoading(false);
        job.refreshCode(); //初始化验证码
      }
    }
  };
  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };
</script>

<style lang="less" scoped>
  /* This was made with GlassGenerator.netlify.app */

  .glass-container {
    width: 30rem;
    height: 25rem;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 20px;
    border-radius: 10px;
    backdrop-filter: blur(7px);
    background-color: rgba(225, 225, 239, 0.5);
    box-shadow: rgba(181, 181, 181, 0.3) 2px 8px 8px;
  }
  .login-form-wrapper {
    height: 100%;
    // padding: 20px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    .login-form-title {
      // margin-bottom: 20px;
    }
  }
  .login-form {
    &-wrapper {
      width: 320px;
    }

    &-title {
      color: var(--color-text-1);
      font-weight: 500;
      font-size: 24px;
      line-height: 32px;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
  }
</style>
